﻿using Company.Config;
using Company.Hardware.Acs;
using Company.IO;
using Company.Share.Events;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Threading;

namespace Company.Main.ViewModels
{
    public class DigitalInputViewModel : BindableBase
    {
        #region 字段
        private ObservableCollection<EIN> eINs;
        private DispatcherTimer UpDataInputTimer = new DispatcherTimer();
        private bool isAcsConnected;
        private bool IsRunningUpData = false;
        #endregion
        #region 属性
        public ObservableCollection<EIN> EINs
        {
            get { return eINs; }
            set { eINs = value; RaisePropertyChanged(); }
        }
        public bool IsAcsConnected
        {
            get { return isAcsConnected; }
            set { isAcsConnected = value; RaisePropertyChanged(); }
        }
        public AcsControllerProvider AcsControllerProvider { get; private set; }
        #endregion
        public DigitalInputViewModel(AcsControllerProvider acsControllerProvider,
                                     ConfigProvider configProvider,
                                     IEventAggregator eventAggregator)
        {
            // 从Ioc中获取对象实例
            AcsControllerProvider = acsControllerProvider;
            // 从配置提供者中获取配置信息
            EINs = configProvider.IoConfig.Input.EINs;
            // 注册连接事件
            AcsControllerProvider.AcsController.AcsDisconnecting += () =>
            {
                //if (tokenSource == null) return;
                //// 线程取消
                //tokenSource.Cancel();
                UpDataInputTimer.Stop();
                IsRunningUpData = false;
            };
            UpDataInputTimer.Interval = TimeSpan.FromMilliseconds(50);
            UpDataInputTimer.Tick += (s, e) => ReadDigitalInputCyclically();
            // 使用事件聚合器订阅
            eventAggregator.GetEvent<AcsControllerConnectedEvent>().Subscribe((obj) =>
            {
                IsAcsConnected = obj;
                if (IsAcsConnected)
                {
                    if (!IsRunningUpData)
                    {
                        //_GetDataFromAcsControllerTask = new Task(ReadDigitalInputCyclically, cancellationToken, TaskCreationOptions.LongRunning);//线程读取
                        //_GetDataFromAcsControllerTask.Start();

                        //IsRunningUpData = true;
                        //_GetDataFromAcsControllerTask.ContinueWith(t => 
                        //{ 
                        //    IsRunningUpData = false; 
                        //});
                        IsRunningUpData = true;
                        UpDataInputTimer.Start();
                    }
                }
            });
        }
        #region 线程读取
        /// <summary>
        /// 循环读取数字量输入
        /// </summary>
        private void ReadDigitalInputCyclically()
        {
            if (AcsControllerProvider.AcsController.IsConnected)
            {
                //线程内读取数据
                foreach (var item in EINs)
                {
                    ReadDigitalInput(item.Variables);
                }
            }
        }
        /// <summary>
        /// 读取数字量输入
        /// </summary>
        /// <param name="digitalIOs"></param>
        private void ReadDigitalInput(ObservableCollection<Variable> Variables)
        {
            if (!AcsControllerProvider.AcsController.IsConnected) return;
            foreach (Variable item in Variables)
            {
                var sResponse = AcsControllerProvider.AcsController.SendCommand("?" + item.Symbol);
                var sResult = Regex.Replace(sResponse, @"[^0-9]", "");
                if (sResult == "1")
                    item.Value = "TRUE";
                else
                    item.Value = "FALSE";
            }
        }
        #endregion
    }
}
